package com.example.demo.common.dao;

import com.example.demo.common.Query;
import com.example.demo.common.TableResultResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangting on 30/01/2018.
 */
public class BaseMapper<M extends Mapper<T>,T> {

    @Autowired
    protected M mapper;
    public void setMapper(M mapper){
        this.mapper=mapper;
    }

    public T selectOne(T entity){
        return mapper.selectOne(entity);
    }

    public T selectById(Object id){
        return mapper.selectByPrimaryKey(id);
    }

    public List<T> selectList(T entity){
        return mapper.select(entity);
    }

    public List<T> selectAllList(){
        return mapper.selectAll();
    }

    public int selectCount(T entity){return mapper.selectCount(entity);}

    public int insert(T entity){
        return mapper.insertSelective(entity);
    }

    public int delete (T entity){
        return mapper.delete(entity);
    }

    public int deleteById(Object id){
        return mapper.deleteByPrimaryKey(id);
    }

    public void updateById(T entity) {
        mapper.updateByPrimaryKey(entity);
    }


    public void updateSelectiveById(T entity) {
        mapper.updateByPrimaryKeySelective(entity);

    }

    public List<T> selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    public int selectCountByExample(Object example) {
        return mapper.selectCountByExample(example);
    }

    public TableResultResponse<T> selectByQuery(Query query) {
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        if(query.entrySet().size()>0) {
            Example.Criteria criteria = example.createCriteria();
            for (Map.Entry<String, Object> entry : query.entrySet()) {
                criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
            }
        }
        Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
        List<T> list = mapper.selectByExample(example);
        return new TableResultResponse<T>(result.getTotal(), list);
    }

}
